package com.ruoyi.demo.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.demo.vo.SnWareHouseDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.*;

@Service
@Slf4j
public class JiandaoyunService {
    @Autowired
    private ObjectMapper objectMapper;

    @Value("${jiandaoyun.appId}")
    private String jdyAppId;

    @Value("${jiandaoyun.entryId}")
    private String jdyEntryId;

    @Value("${jiandaoyun.token}")
    private String jdyToken;

    @Value("${jiandaoyun.batch-create-url}")
    private String batchCreateUrl; // 完整接口URL：https://api.jiandaoyun.com/api/v5/app/entry/data/batch_create

    // 每批发送的最大条数
    private static final int BATCH_SIZE = 100;

    /**
     * 发送批量数据到简道云（自动按100条一批次分割）
     * @param dataList 业务数据列表（SnWareHouseDataVo）
     * @return 所有批次的简道云接口响应，以JSON数组形式返回
     */
    public String batchSendToJdy(List<SnWareHouseDataVo> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            log.info("没有数据需要发送到简道云");
            return "[]";
        }

        List<String> allResponses = new ArrayList<>();
        int totalSize = dataList.size();
        log.info("开始分批发送数据到简道云，总条数：{}，每批最多{}条", totalSize, BATCH_SIZE);

        // 按批次分割并发送
        for (int start = 0; start < totalSize; start += BATCH_SIZE) {
            int end = Math.min(start + BATCH_SIZE, totalSize);
            List<SnWareHouseDataVo> subList = dataList.subList(start, end);
            log.info("处理第{}批数据（条数：{}）", (start / BATCH_SIZE) + 1, subList.size());

            // 发送当前批次
            String batchResponse = sendSingleBatch(subList);
            allResponses.add(batchResponse);
        }

        log.info("所有批次数据发送完成，共{}批", allResponses.size());

        // 将所有批次响应转换为JSON返回
        try {
            return objectMapper.writeValueAsString(allResponses);
        } catch (JsonProcessingException e) {
            log.error("合并响应结果失败", e);
            throw new RuntimeException("合并响应结果失败：" + e.getMessage());
        }
    }

    /**
     * 发送单批次数据到简道云
     * @param subList 单批次数据列表（不超过100条）
     * @return 该批次的接口响应
     */
    private String sendSingleBatch(List<SnWareHouseDataVo> subList) {
        try {
            // 1. 构造请求参数Map
            Map<String, Object> requestParam = new HashMap<>();
            requestParam.put("app_id", jdyAppId);
            requestParam.put("entry_id", jdyEntryId);
            requestParam.put("transaction_id", UUID.randomUUID().toString()); // 每批使用独立的事务ID
            requestParam.put("data_list", convertToJdyDataList(subList));
            requestParam.put("is_start_workflow",true);

            // 2. 转换为JSON字符串（使用Jackson）
            String jsonParam = objectMapper.writeValueAsString(requestParam);
            log.debug("简道云批次请求参数：{}", jsonParam);

            // 3. 发送POST请求
            HttpResponse response = HttpRequest.post(batchCreateUrl)
                    .header("Authorization", "Bearer " + jdyToken)
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .body(jsonParam)
                    .timeout(600000)
                    .execute();

            // 4. 获取响应结果
            String result = response.body();
            log.debug("简道云批次响应结果：{}", result);

            return result;
        } catch (JsonProcessingException e) {
            log.error("批次参数转换JSON失败", e);
            throw new RuntimeException("参数格式错误：" + e.getMessage());
        } catch (Exception e) {
            log.error("调用简道云接口失败", e);
            throw new RuntimeException("发送数据失败：" + e.getMessage());
        }
    }


    /**
     * 将业务数据List<SnWareHouseDataVo>转换为简道云data_list格式
     */
    private List<Map<String, Object>> convertToJdyDataList(List<SnWareHouseDataVo> dataList) {
        List<Map<String, Object>> jdyDataList = new ArrayList<>();

        for (SnWareHouseDataVo vo : dataList) {
            Map<String, Object> jdyData = new HashMap<>();
            jdyData.put("sn", Collections.singletonMap("value", vo.getSn()));
            jdyData.put("zjbm", Collections.singletonMap("value", vo.getZjbm()));
            jdyData.put("zjxh", Collections.singletonMap("value", vo.getZjxh()));
            jdyData.put("zjgg", Collections.singletonMap("value", vo.getZjgg()));
            jdyData.put("dybm", Collections.singletonMap("value", vo.getDybm()));
            jdyData.put("dyms", Collections.singletonMap("value", vo.getDyms()));
            jdyData.put("dysn", Collections.singletonMap("value", vo.getDysn()));
            jdyData.put("kzbbm", Collections.singletonMap("value", vo.getKzbbm()));
            jdyData.put("kzbms", Collections.singletonMap("value", vo.getKzbms()));
            jdyData.put("kzbsn", Collections.singletonMap("value", vo.getKzbsn()));
            jdyData.put("qbhbm", Collections.singletonMap("value", vo.getQbhbm()));
            jdyData.put("qbhms", Collections.singletonMap("value", vo.getQbhms()));
            jdyData.put("qbhsn", Collections.singletonMap("value", vo.getQbhsn()));
            jdyData.put("qbhklcd", Collections.singletonMap("value", vo.getQbhklcd()));
            jdyData.put("rksj", Collections.singletonMap("value", vo.getRksj()));
            jdyDataList.add(jdyData);
        }

        return jdyDataList;
    }
}